# 学生成绩管理模块功能接口
import numpy as np
from flask import request, jsonify, send_from_directory, Blueprint
import exts
import sqlite3
from flask_jwt_extended import jwt_required, get_jwt
import pandas as pd
import os

scores_blueprint = Blueprint('scores', __name__)


# 学生成绩上传模板下载
@scores_blueprint.route('/download/score-template/<string:template_code>', methods=['GET'])
@jwt_required()
@exts.permission_required('scores', 'R')
def download_score_template(template_code):
    """根据请求参数提供相应的考试成绩上传模板下载"""
    template_filenames = {
        "1": "成绩上传模板（含省市排名）.xlsx",
        "2": "成绩上传模板（通用）.xlsx",
    }
    template_filename = template_filenames.get(template_code)
    if not template_filename:
        # 如果提供的代码不在映射表中，返回错误信息
        return jsonify({
            "code": 400,
            "details": "提供的模板代码无效",
            "message": "请求参数错误",
            "status": "error"
        }), 400

    template_path = os.path.join("static/upload-templates/score-templates", template_filename)
    if not os.path.exists(template_path):
        # 如果文件不存在，返回错误信息
        return jsonify({
            "code": 404,
            "details": f"模板文件'{template_filename}'不存在",
            "message": "请求参数错误",
            "status": "error"
        }), 404

    try:
        return send_from_directory("static/upload-templates/score-templates", template_filename, as_attachment=True)
    except Exception as e:
        return jsonify({
            "code": 500,
            "details": str(e),
            "message": "下载模板时发生错误",
            "status": "error"
        }), 500


# 页面添加学生成绩
@scores_blueprint.route('/add', methods=['POST'])
@jwt_required()
@exts.permission_required('scores', 'C')
def add_score():
    """添加学生成绩"""
    if request.json is None:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "请求参数应为 JSON 格式"
        }), 400
    elif request.json.get('student_id') is None or request.json.get('exam_id') is None:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "student_id 和 exam_id 参数不能为空"
        }), 400
    data = request.json

    fields = [
        "student_id", "school_id", "year", "student_grade", "exam_id", "class",
        "Sum", "SumB", "SumD", "SumF", "SumBF", "SumDF", "SumRankProvince",
        "SumRankCity", "Yuwen", "YuwenB", "YuwenD", "YuwenF", "YuwenBF", "YuwenDF",
        "YuwenRankProvince", "YuwenRankCity", "Shuxue", "ShuxueB", "ShuxueD", "ShuxueF",
        "ShuxueBF", "ShuxueDF", "ShuxueRankProvince", "ShuxueRankCity", "Waiyu", "WaiyuB",
        "WaiyuD", "WaiyuF", "WaiyuBF", "WaiyuDF", "WaiyuRankProvince", "WaiyuRankCity",
        "WaiyuType", "Wuli", "WuliB", "WuliD", "WuliF", "WuliBF", "WuliDF",
        "WuliRankProvince", "WuliRankCity", "Huaxue", "HuaxueB", "HuaxueD", "HuaxueF",
        "HuaxueBF", "HuaxueDF", "HuaxueRankProvince", "HuaxueRankCity", "Shengwu", "ShengwuB",
        "ShengwuD", "ShengwuF", "ShengwuBF", "ShengwuDF", "ShengwuRankProvince", "ShengwuRankCity",
        "Lishi", "LishiB", "LishiD", "LishiF", "LishiBF", "LishiDF", "LishiRankProvince",
        "LishiRankCity", "Zhengzhi", "ZhengzhiB", "ZhengzhiD", "ZhengzhiF", "ZhengzhiBF",
        "ZhengzhiDF", "ZhengzhiRankProvince", "ZhengzhiRankCity", "Dili", "DiliB", "DiliD",
        "DiliF", "DiliBF", "DiliDF", "DiliRankProvince", "DiliRankCity", "Zonghe",
        "ZongheB", "ZongheD", "ZongheF", "ZongheBF", "ZongheDF", "ZongheRankProvince",
        "ZongheRankCity", "examtype", "show"
    ]
    # 过滤掉其他参数
    data = {key: data[key] for key in data.keys() if key in fields}

    school_id = data.get('school_id')
    if school_id is None:
        school_id = get_jwt()['school_id']
        data['school_id'] = school_id
    conn = None
    try:
        conn = exts.get_db()
        cur = conn.cursor()
        if data.get('year') is None or data.get('student_grade') is None:
            cur.execute("SELECT year, student_grade FROM Exam WHERE exam_id = ? AND school_id = ?"
                        "UNION SELECT year, student_grade FROM HistoryExam WHERE exam_id = ? AND school_id = ?",
                        (data['exam_id'], school_id, data['exam_id'], school_id))
            student_info = cur.fetchone()
            data['year'] = student_info[0] if student_info else None
            data['student_grade'] = student_info[1] if student_info else None
        data['id'] = exts.get_latest_id('scores')
        if data['id'] is None:
            return jsonify({
                "code": 500,
                "status": "error",
                "message": "服务器内部错误",
                "details": "无法获取最新的学生成绩ID"
            }), 500
        sql = f"INSERT INTO CurrentScoreD ({', '.join(data.keys())}) VALUES ({', '.join(['?'] * len(data))})"
        cur.execute(sql, list(data.values()))
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "学生成绩添加成功",
            "data": {"id": data['id']}
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": f"错误详情：{e}"
        }), 500
    finally:
        if conn:
            exts.close_db(conn)


# 页面上传文件批量导入学生成绩
@scores_blueprint.route('/import', methods=['POST'])
@jwt_required()
@exts.permission_required('scores', 'C')
def import_scores():
    """批量导入学生成绩"""
    # 验证参数
    try:
        data = {
            "school_id": request.form['school_id'] if 'school_id' in request.form else get_jwt()['school_id'],
            "student_grade": request.form['student_grade'] if 'student_grade' in request.form else None,
            "year": request.form['year'] if 'year' in request.form else None,
            "import_type": request.form['import_type'] if 'import_type' in request.form else None,
            "exam_id": request.form['exam_id'] if 'exam_id' in request.form else None,
            "examtype": request.form['examtype'] if 'examtype' in request.form else None,
            "show": request.form['show'] if 'show' in request.form else None
        }
        for key, value in data.items():
            if value is None or value == '':
                raise ValueError(f"参数 {key} 缺少或为空，请提供有效的 {key} 参数")
    except ValueError as e:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": str(e)
        }), 400
    uploaded_files = request.files.getlist('files')
    if not uploaded_files or uploaded_files[0].filename == '':
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "未上传任何文件"
        }), 400
    for uploaded_file in uploaded_files:
        if not uploaded_file.filename.endswith('.xlsx'):
            return jsonify({
                "code": 400,
                "status": "error",
                "message": "请求参数错误",
                "details": "上传的文件不是有效的 Excel 文件"
            }), 400
    if data["import_type"] not in ["supplement", "overwrite"]:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "import_type 参数应为 'supplement' 或 'overwrite'"
        }), 400
    if data["import_type"] == "overwrite":
        conn = None
        try:
            conn = exts.get_db()
            cur = conn.cursor()
            # 如果是覆盖导入，首先删除指定条件下的现有记录
            cur.execute("""
                DELETE FROM CurrentScoreD WHERE year = ? AND student_grade = ? AND exam_id = ? AND school_id = ?
            """, (data['year'], data['student_grade'], data['exam_id'], data['school_id']))
            conn.commit()
        except Exception as e:
            if conn:
                conn.rollback()
            return jsonify({
                "code": 500,
                "status": "error",
                "message": "服务器内部错误",
                "details": f"错误详情：{e}"
            }), 500
        finally:
            if conn:
                exts.close_db(conn)
    results = []
    for uploaded_file in uploaded_files:
        try:
            df = pd.read_excel(uploaded_file, sheet_name="Sheet1")
            result = exts.upload_scores(df, data)
            results.append({'filename': uploaded_file.filename, **result})
        except Exception as e:
            results.append({'filename': uploaded_file.filename, 'status': 'error', 'message': f'处理文件时出错: {e}'})

    return jsonify({"code": 200, "status": "success", "message": "文件处理完成", "details": results}), 200


# 页面更新学生成绩
@scores_blueprint.route('/update/<int:id_>', methods=['PUT'])
@jwt_required()
@exts.permission_required('scores', 'U')
def update_score(id_):
    """更新指定ID的学生成绩"""
    if id_ is None:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "id 参数不能为空"
        }), 400
    data = request.json
    fields = [
        "student_id", "school_id", "year", "student_grade", "exam_id", "class",
        "Sum", "SumB", "SumD", "SumF", "SumBF", "SumDF", "SumRankProvince",
        "SumRankCity", "Yuwen", "YuwenB", "YuwenD", "YuwenF", "YuwenBF", "YuwenDF",
        "YuwenRankProvince", "YuwenRankCity", "Shuxue", "ShuxueB", "ShuxueD", "ShuxueF",
        "ShuxueBF", "ShuxueDF", "ShuxueRankProvince", "ShuxueRankCity", "Waiyu", "WaiyuB",
        "WaiyuD", "WaiyuF", "WaiyuBF", "WaiyuDF", "WaiyuRankProvince", "WaiyuRankCity",
        "WaiyuType", "Wuli", "WuliB", "WuliD", "WuliF", "WuliBF", "WuliDF",
        "WuliRankProvince", "WuliRankCity", "Huaxue", "HuaxueB", "HuaxueD", "HuaxueF",
        "HuaxueBF", "HuaxueDF", "HuaxueRankProvince", "HuaxueRankCity", "Shengwu", "ShengwuB",
        "ShengwuD", "ShengwuF", "ShengwuBF", "ShengwuDF", "ShengwuRankProvince", "ShengwuRankCity",
        "Lishi", "LishiB", "LishiD", "LishiF", "LishiBF", "LishiDF", "LishiRankProvince",
        "LishiRankCity", "Zhengzhi", "ZhengzhiB", "ZhengzhiD", "ZhengzhiF", "ZhengzhiBF",
        "ZhengzhiDF", "ZhengzhiRankProvince", "ZhengzhiRankCity", "Dili", "DiliB", "DiliD",
        "DiliF", "DiliBF", "DiliDF", "DiliRankProvince", "DiliRankCity", "Zonghe",
        "ZongheB", "ZongheD", "ZongheF", "ZongheBF", "ZongheDF", "ZongheRankProvince",
        "ZongheRankCity", "examtype", "show"
    ]
    # 过滤掉其他参数
    data = {key: data[key] for key in data.keys() if key in fields}

    if data is None:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "请求参数应为 JSON 格式"
        }), 400
    conn = None
    try:
        conn = exts.get_db()
        cur = conn.cursor()
        cur.execute(f"UPDATE CurrentScoreD SET {', '.join([f'{key} = ?' for key in data.keys()])} WHERE id = ?",
                    list(data.values()) + [id_])
        if cur.rowcount == 0:
            cur.execute(f"UPDATE HistoryScoreD SET {', '.join([f'{key} = ?' for key in data.keys()])} WHERE id = ?",
                        list(data.values()) + [id_])
            if cur.rowcount == 0:
                return jsonify({
                    "code": 404,
                    "status": "error",
                    "message": "未找到指定记录",
                    "details": f"未找到 ID 为 {id_} 的学生成绩记录"
                }), 404
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "学生成绩更新成功",
            "data": {"id": id_}
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": f"错误详情：{e}"
        }), 500
    finally:
        if conn:
            exts.close_db(conn)


# 页面查询学生成绩
@scores_blueprint.route('/query', methods=['GET'])
@jwt_required()
@exts.permission_required('scores', 'R')
def query_scores():
    """组合条件查询学生成绩"""
    school_id = request.args.get('school_id', get_jwt()['school_id'], type=int)
    student_id = request.args.get('student_id', None, type=int)
    year = request.args.get('year', None, type=str)
    student_name = request.args.get('student_name', None, type=str)
    student_grade = request.args.get('student_grade', None, type=str)
    class_ = request.args.get('class', None, type=str)
    exam_id = request.args.get('exam_id', None, type=int)
    examtype = request.args.get('examtype', None, type=int)
    show = request.args.get('show', None, type=int)
    WaiyuType = request.args.get('WaiyuType', None, type=int)
    page = request.args.get('page', 1, type=int)
    page_size = request.args.get('page_size', 10, type=int)

    if page < 1 or page_size < 1:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "page 和 page_size 必须大于 0"
        }), 400

    offset = (page - 1) * page_size

    conditions_current = []
    conditions_history = []
    params_current = []
    params_history = []

    if school_id:
        conditions_current.append("c.school_id = ?")
        conditions_history.append("h.school_id = ?")
        params_current.append(school_id)
        params_history.append(school_id)
    if student_id:
        conditions_current.append("c.student_id = ?")
        conditions_history.append("h.student_id = ?")
        params_current.append(student_id)
        params_history.append(student_id)
    if year:
        conditions_current.append("c.year = ?")
        conditions_history.append("h.year = ?")
        params_current.append(year)
        params_history.append(year)
    if student_grade:
        conditions_current.append("c.student_grade = ?")
        conditions_history.append("h.student_grade = ?")
        params_current.append(student_grade)
        params_history.append(student_grade)
    if class_:
        conditions_current.append("c.class = ?")
        conditions_history.append("h.class = ?")
        params_current.append(class_)
        params_history.append(class_)
    if exam_id:
        conditions_current.append("c.exam_id = ?")
        conditions_history.append("h.exam_id = ?")
        params_current.append(exam_id)
        params_history.append(exam_id)
    if examtype is not None:
        conditions_current.append("c.examtype = ?")
        conditions_history.append("h.examtype = ?")
        params_current.append(examtype)
        params_history.append(examtype)
    if show is not None:
        conditions_current.append("c.show = ?")
        conditions_history.append("h.show = ?")
        params_current.append(show)
        params_history.append(show)
    if WaiyuType is not None:
        conditions_current.append("c.WaiyuType = ?")
        conditions_history.append("h.WaiyuType = ?")
        params_current.append(WaiyuType)
        params_history.append(WaiyuType)

    # student_name 条件共用
    student_name_condition = ""
    if student_name:
        student_name_condition = "AND (cs.student_name LIKE ? OR ar.student_name LIKE ?)"
        params_current.extend([f"%{student_name}%", f"%{student_name}%"])
        params_history.extend([f"%{student_name}%", f"%{student_name}%"])

    where_clause_current = " AND ".join(conditions_current) if conditions_current else "1=1"
    where_clause_history = " AND ".join(conditions_history) if conditions_history else "1=1"

    sql = f"""
        SELECT * FROM (
            SELECT DISTINCT c.id, c.student_id, COALESCE(cs.student_name, ar.student_name) as student_name, 
                   c.year, c.student_grade, c.class, c.Sum, c.SumB, c.SumD,
                   c.Yuwen, c.YuwenB, c.YuwenD, c.Shuxue, c.ShuxueB, c.ShuxueD, c.Waiyu, c.WaiyuB, c.WaiyuD, 
                   c.WaiyuType, c.Wuli, c.WuliB, c.WuliD, c.Huaxue, c.HuaxueB, c.HuaxueD, c.Shengwu, c.ShengwuB, 
                   c.ShengwuD, c.Zhengzhi, c.ZhengzhiB, c.ZhengzhiD, c.Lishi, c.LishiB, c.LishiD, c.Dili, c.DiliB, 
                   c.DiliD, c.show, c.school_id, sc.school_name, c.exam_id, 
                   COALESCE(e.exam_name, he.exam_name) as exam_name
            FROM CurrentScoreD c
            LEFT JOIN CurrentStudent cs ON c.student_id = cs.student_id
            LEFT JOIN AllStudentRecord ar ON c.student_id = ar.student_id
            LEFT JOIN School sc ON c.school_id = sc.school_id
            LEFT JOIN Exam e ON c.exam_id = e.exam_id
            LEFT JOIN HistoryExam he ON c.exam_id = he.exam_id
            WHERE {where_clause_current} {student_name_condition}
            UNION ALL
            SELECT DISTINCT  h.id, h.student_id, COALESCE(cs.student_name, ar.student_name) as student_name, 
                   h.year, h.student_grade, h.class, h.Sum, h.SumB, h.SumD,
                   h.Yuwen, h.YuwenB, h.YuwenD, h.Shuxue, h.ShuxueB, h.ShuxueD, h.Waiyu, h.WaiyuB, h.WaiyuD, 
                   h.WaiyuType, h.Wuli, h.WuliB, h.WuliD, h.Huaxue, h.HuaxueB, h.HuaxueD, h.Shengwu, h.ShengwuB, 
                   h.ShengwuD, h.Zhengzhi, h.ZhengzhiB, h.ZhengzhiD, h.Lishi, h.LishiB, h.LishiD, h.Dili, h.DiliB, 
                   h.DiliD, h.show, h.school_id, sc.school_name, h.exam_id, 
                   COALESCE(e.exam_name, he.exam_name) as exam_name
            FROM HistoryScoreD h
            LEFT JOIN CurrentStudent cs ON h.student_id = cs.student_id
            LEFT JOIN AllStudentRecord ar ON h.student_id = ar.student_id
            LEFT JOIN School sc ON h.school_id = sc.school_id
            LEFT JOIN Exam e ON h.exam_id = e.exam_id
            LEFT JOIN HistoryExam he ON h.exam_id = he.exam_id
            WHERE {where_clause_history} {student_name_condition}
        ) AS combined_results
        ORDER BY id DESC
        LIMIT ? OFFSET ?
    """

    sql_count = f"""
        SELECT COUNT(*) AS total FROM (
            SELECT DISTINCT  c.id
            FROM CurrentScoreD c
            LEFT JOIN CurrentStudent cs ON c.student_id = cs.student_id
            LEFT JOIN AllStudentRecord ar ON c.student_id = ar.student_id
            LEFT JOIN School sc ON c.school_id = sc.school_id
            LEFT JOIN Exam e ON c.exam_id = e.exam_id
            LEFT JOIN HistoryExam he ON c.exam_id = he.exam_id
            WHERE {where_clause_current} {student_name_condition}
            UNION ALL
            SELECT DISTINCT  h.id
            FROM HistoryScoreD h
            LEFT JOIN CurrentStudent cs ON h.student_id = cs.student_id
            LEFT JOIN AllStudentRecord ar ON h.student_id = ar.student_id
            LEFT JOIN School sc ON h.school_id = sc.school_id
            LEFT JOIN Exam e ON h.exam_id = e.exam_id
            LEFT JOIN HistoryExam he ON h.exam_id = he.exam_id
            WHERE {where_clause_history} {student_name_condition}
        ) AS combined_results
    """

    all_params = params_current + params_history + [page_size, offset]
    count_params = params_current + params_history
    conn = None
    try:
        conn = exts.get_db()
        cursor = conn.cursor()

        # 查询总记录数
        cursor.execute(sql_count, count_params)
        total_records = cursor.fetchone()[0]
        total_pages = (total_records + page_size - 1) // page_size

        if total_records == 0:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到符合条件的学生成绩"
            }), 404

        if 0 < total_pages < page:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "请求的页码超出范围",
                "details": f"请求的页码超出了最大页数（{total_pages}页）"
            }), 404

        # 查询当前页的数据
        cursor.execute(sql, all_params)
        results = cursor.fetchall()

        # 将结果转换为列的形式
        columns = {key: [row[key] for row in results] for key in results[0].keys()}

        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": {
                "total_records": total_records,
                "total_pages": total_pages,
                "current_page": page,
                "page_size": len(results),
                "results": columns
            }
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 根据记录ID查询学生成绩记录
@scores_blueprint.route('/<int:id_>', methods=['GET'])
@jwt_required()
@exts.permission_required('scores', 'R')
def get_score_by_id(id_):
    """根据ID查询学生成绩记录"""
    # 检查参数是否为空
    if id_ is None:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "id 参数不能为空"
        }), 400

    sql = f"""
        SELECT DISTINCT
            c.*, 
            COALESCE(cs.student_name, ar.student_name) AS student_name,
            sc.school_name,
            COALESCE(e.exam_name, he.exam_name) AS exam_name
        FROM
            CurrentScoreD c
        LEFT JOIN
            CurrentStudent cs ON c.student_id = cs.student_id
        LEFT JOIN
            AllStudentRecord ar ON c.student_id = ar.student_id
        LEFT JOIN
            School sc ON c.school_id = sc.school_id
        LEFT JOIN
            Exam e ON c.exam_id = e.exam_id
        LEFT JOIN
            HistoryExam he ON c.exam_id = he.exam_id
        WHERE
            c.id = {id_}
        UNION ALL
        SELECT DISTINCT
            h.*, 
            COALESCE(cs.student_name, ar.student_name) AS student_name,
            sc.school_name,
            COALESCE(e.exam_name, he.exam_name) AS exam_name
        FROM
            HistoryScoreD h
        LEFT JOIN
            CurrentStudent cs ON h.student_id = cs.student_id
        LEFT JOIN
            AllStudentRecord ar ON h.student_id = ar.student_id
        LEFT JOIN
            School sc ON h.school_id = sc.school_id
        LEFT JOIN
            Exam e ON h.exam_id = e.exam_id
        LEFT JOIN
            HistoryExam he ON h.exam_id = he.exam_id
        WHERE
            h.id = {id_}
    """

    conn = None
    try:
        conn = exts.get_db()
        cursor = conn.cursor()
        cursor.execute(sql)
        result = cursor.fetchone()
        if result is None:
            return jsonify({
                "code": 404,
                "status": "error",
                "message": "未找到指定记录",
                "details": f"未找到 ID 为 {id_} 的学生成绩记录"
            }), 404

        result = dict(zip([column[0] for column in cursor.description], result))

        return jsonify({
            "code": 200,
            "status": "success",
            "message": "查询成功",
            "data": result
        }), 200
    except Exception as e:
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": str(e)
        }), 500
    finally:
        if conn:
            conn.close()


# 页面删除学生成绩
@scores_blueprint.route('/delete', methods=['DELETE'])
@jwt_required()
@exts.permission_required('scores', 'D')
def scores_d():
    """删除学生成绩记录"""
    data = request.json.get('data', None)
    if data is None:
        return jsonify({
            "code": 400,
            "status": "error",
            "message": "请求参数错误",
            "details": "请求参数应为 JSON 格式，且包含 data 字段"
        }), 400
    conn = None
    try:
        conn = exts.get_db()
        cur = conn.cursor()
        result = []
        # 遍历 data 中的 ID，逐个删除
        for id_ in data:
            cur.execute("DELETE FROM CurrentScoreD WHERE id = ?", (id_,))
            if cur.rowcount == 0:
                cur.execute("DELETE FROM HistoryScoreD WHERE id = ?", (id_,))
                if cur.rowcount == 0:
                    result.append({"id": id_, "status": "error", "message": "未找到指定记录"})
                else:
                    result.append({"id": id_, "status": "success", "message": "删除成功"})
            else:
                result.append({"id": id_, "status": "success", "message": "删除成功"})
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "学生成绩删除成功",
            "data": result
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": f"错误详情：{e}"
        }), 500
    finally:
        if conn:
            exts.close_db(conn)


# 页面学生成绩迁移
@scores_blueprint.route('/migrate', methods=['POST'])
@jwt_required()
@exts.permission_required('scores', 'M')
def scores_m():
    """学生成绩迁移"""
    sql = """
    INSERT INTO HistoryScoreD
    SELECT * FROM CurrentScoreD;
    DELETE FROM CurrentScoreD;
    """
    conn = None
    try:
        conn = exts.get_db()
        cur = conn.cursor()
        cur.executescript(sql)
        conn.commit()
        return jsonify({
            "code": 200,
            "status": "success",
            "message": "学生成绩迁移成功"
        }), 200
    except Exception as e:
        if conn:
            conn.rollback()
        return jsonify({
            "code": 500,
            "status": "error",
            "message": "服务器内部错误",
            "details": f"错误详情：{e}"
        }), 500
    finally:
        if conn:
            exts.close_db(conn)
